<?php

namespace app\admin\controller\bonus;

use app\common\controller\Backend;
use app\common\model\general\LihuaCity;
use app\common\model\LihuaUserbonus;

/**
 * 发放明细
 *
 * @icon fa fa-circle-o
 */
class Userbonus extends Backend
{
    protected $cityLimit = true;

    /**
     * LihuaUserbonus模型对象
     * @var LihuaUserbonus
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new LihuaUserbonus();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['user' => function ($query) {$query->field('username,mobile');}])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user' => function ($query) {$query->field('username,mobile');}])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $cityArr = LihuaCity::getCityArr();
            $list = collection($list)->toArray();
            $now = date('Y-m-d');
            foreach ($list as $k => $v) {
                $list[$k]['city_name'] = isset($cityArr[$v['city_id']]) ? $cityArr[$v['city_id']] : '';
                if ($v['status'] == 0 &&  $now > $v['end_date']) {
                    $list[$k]['status'] = 2;
                    $this->model->where('id', $v['id'])->setField('status', 2);
                }
            }

            $result  = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

}
